package tech.mhuang.ext.elasticsearch.sample;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import tech.mhuang.ext.elasticsearch.admin.ESBuilder;
import tech.mhuang.ext.elasticsearch.admin.ESFramework;
import tech.mhuang.ext.elasticsearch.admin.factory.IESFactory;
import tech.mhuang.ext.elasticsearch.server.annoation.ESTable;

import java.io.IOException;

/**
 *
 * 测试
 *
 * @author mhuang
 * @since 1.0.0
 */
@Slf4j
public class TestSample {

    public static void main(String[] args) {
        //获取ES构建类
        ESBuilder.Builder builder = ESBuilder.builder();
        //创建ES生产
        ESBuilder.ProducerBuilder producerBuilder = builder.createProducerBuilder();
        //绑定一个zhangsan地址210到framework,可同时绑定多个
        ESFramework framework = builder.bindProducer("zhangsan",
                      producerBuilder.ip("192.168.1.210").builder()).builder();
        //启动ES平台
        framework.start();
        //根据绑定的key获取对应的工厂
        IESFactory factory = framework.getFactory("zhangsan");
        try {
            //ES新增
            IndexResponse response = factory.insert("{\"age\":22}","test","test");
            log.info("新增1:{}",response);
            Test test = new Test();
            IndexResponse response2 = factory.insert(test);
            log.info("新增2:{}",response2);
            String id = response2.getId();
            test.setName("你好");
            //ES修改
            UpdateResponse response3 = factory.update(test,id);
            log.info("修改:{}",response3);
            //ES删除数据
            DeleteResponse response4 = factory.delete("test","test",id);
            log.info("删除:{}",response4);
            //ES删除索引及数据
            AcknowledgedResponse response5 = factory.delete("test");
            log.info("删除索引:{}",response5);
            //获取RestHighLevelClient对象
            RestHighLevelClient client = factory.getClient();
            log.info("打印信息{}",client.info(RequestOptions.DEFAULT));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Data
    @ESTable(index = "test", type = "test")
    static class Test {
        private String name = "张三";
    }
}
